package com.jishaokang.service.impl;

import com.jishaokang.base.Result;
import com.jishaokang.cache.ResultCache;
import com.jishaokang.dao.UserDAO;
import com.jishaokang.model.dto.User;
import com.jishaokang.model.vo.UserVO;
import com.jishaokang.service.UserService;
import com.jishaokang.util.EncyptUtil;
import com.jishaokang.util.ForbidUtil;
import com.jishaokang.util.TokenUtil;
import com.jishaokang.util.VerificationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by NANA_Final on 2019/6/21.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private ForbidUtil forbidUtil;
    @Autowired
    private VerificationUtil verificationUtil;

    @Override
    public Result login(User user) throws NoSuchAlgorithmException {
        String passwordInDB = userDAO.selectPasswordByUsername(user.getUsername());
        System.out.println(user);
        System.out.println(passwordInDB);
        System.out.println(1);
        System.out.println(EncyptUtil.encyptPassword(user.getPassword()));
        if (passwordInDB == null) {
            return ResultCache.getDataError(501,"用户不存在");
        }else if (EncyptUtil.encyptPassword(user.getPassword()).equals(passwordInDB)){
            UserVO userVO = userDAO.selectByUsername(user.getUsername());
            System.out.println(userVO);
            String token = tokenUtil.addToken(userVO.getUserId());
            userVO.setToken(token);
            return ResultCache.getDataOk(userVO);
        }else{
            return ResultCache.getDataError(502,"用户名或密码错误");
        }
    }

    @Override
    public Result addUser(User user) throws NoSuchAlgorithmException {
        UserVO userVO = userDAO.selectByUsername(user.getUsername());
        if (userVO != null) return ResultCache.getDataError(501,"用户名已存在");
        user.setPassword(EncyptUtil.encyptPassword(user.getPassword()));
        userDAO.insert(user);
        return ResultCache.OK;
    }

    @Override
    public Result sendVerification(User user) throws IOException {
        verificationUtil.sendVerification(user.getPhone());
        return ResultCache.OK;
    }

    @Override
    public Result loginByVerification(String phone, String verification) throws NoSuchAlgorithmException {
        if (!verificationUtil.checkVerification(phone,verification)){
            return ResultCache.getDataError(501,"验证码错误");
        }
        UserVO userVO = userDAO.selectByPhone(phone);
        if (userVO !=null){
            userVO.setToken(tokenUtil.addToken(userVO.getUserId()));
            return ResultCache.getDataOk(userVO);
        }else{
            User user = new User();
            user.setUsername(phone);
            user.setPassword(EncyptUtil.encyptPassword(phone));
            userDAO.insert(user);
            userVO = userDAO.selectByUsername(phone);
            user.setPhone(phone);
            user.setUserId(userVO.getUserId());
            userDAO.updatePhone(user);
            userVO.setToken(tokenUtil.addToken(user.getUserId()));
            return ResultCache.getDataOk(userVO);
        }
    }

    @Override
    public Result updatePhone(String token, String phone, String verification) {
        if (!verificationUtil.checkVerification(phone,verification)){
            return ResultCache.getDataError(501,"验证码输入错误");
        }
        UserVO userInDB = userDAO.selectByPhone(phone);
        if (userInDB != null) return ResultCache.getDataError(502,"手机号已存在");
        int userId = tokenUtil.getUserIdByToken(token);
        User user = new User();
        user.setUserId(userDAO.selectByUserId(userId).getUserId());
        user.setPhone(phone);
        userDAO.updatePhone(user);
        return ResultCache.OK;
    }

    @Override
    public Result logout(User user) {
        System.out.println(user);
        tokenUtil.removeToken(user.getToken());
        return ResultCache.OK;
    }

    @Override
    public Result getUserCurrent(User user) {
        int userId = tokenUtil.getUserIdByToken(user.getToken());
        UserVO userVO = userDAO.selectByUserId(userId);
        return ResultCache.getDataOk(userVO);
    }

    @Override
    public Result selectUserByUsername(User user) {
        UserVO userVO = userDAO.selectByUsername(user.getUsername());
        return ResultCache.getDataOk(userVO);
    }

    @Override
    public Result selectUserByUserId(User user) {
        UserVO userVO = userDAO.selectByUserId(user.getUserId());
        return ResultCache.getDataOk(userVO);
    }

    @Override
    public Result updateUserPassword(String token, String oldPassword, String password) throws NoSuchAlgorithmException {
        int userId = tokenUtil.getUserIdByToken(token);
        String passwordInDB = userDAO.selectPasswordByUserId(userId);
        User user = new User();
        user.setUserId(userId);
        user.setPassword(EncyptUtil.encyptPassword(oldPassword));
        if (!user.getPassword().equals(passwordInDB)){
            return ResultCache.getDataError(501,"原密码输入错误");
        }
        user.setPassword(EncyptUtil.encyptPassword(password));
        userDAO.updatePassword(user);
        return ResultCache.OK;
    }

    @Override
    public Result updateUser(User user) {
        user.setUserId(tokenUtil.getUserIdByToken(user.getToken()));
        UserVO userVO = userDAO.selectByUserId(user.getUserId());
        if (user.getUsername()!=null && !user.getUsername().equals(userVO.getUsername())){
            UserVO userVOSameName = userDAO.selectByUsername(user.getUsername());
            if (userVOSameName!=null) return ResultCache.getDataError(501,"用户名已存在");
        }else{
            user.setUsername(userVO.getUsername());
        }
        if (user.getUserIntroduction() == null) user.setUserIntroduction(userVO.getUserIntroduction());
        if (user.getAge() == null) user.setAge(userVO.getAge());
        if (user.getPhone() == null) user.setPhone(userVO.getPhone());
        if (user.getEmail() == null) user.setEmail(userVO.getEmail());
        userDAO.update(user);
        return ResultCache.OK;
    }

    public static final String KEYSTRING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    public static final int len = KEYSTRING.length();

    @Override
    public Result updateUserImage(String token, MultipartFile imageFile, HttpServletRequest request) throws IOException {

        Random random = new Random();
        StringBuilder sb = new StringBuilder(new Date().getTime()+"");
        for (int i = 0;i < 50;i++ )
            sb = sb.append(KEYSTRING.charAt(random.nextInt(len)));
        sb.append(".");
        sb.append(imageFile.getOriginalFilename().split("\\.")[1]);
        String path = request.getServletContext().getRealPath("/upload/image/");
        String fileName = sb.toString();
        File targetFile = new File(path, fileName);
        System.out.println(path+"   "+fileName);
        targetFile.createNewFile();
        try {
            imageFile.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        User user = new User();
        user.setUserId(tokenUtil.getUserIdByToken(token));
        user.setUserImage("upload/image/"+fileName);
        userDAO.updateUserImage(user);
        return ResultCache.OK;
    }

    @Override
    public Result updateUserPower(User user) throws ParseException {
        forbidUtil.updateUserPower(user.getUserId(),user.getPower());
        return ResultCache.OK;
    }

    @Override
    public Result selectUserByForbid(User user) {
        int total=userDAO.selectTotalByForbid(user);
        user.setPage((user.getPage()-1)*user.getNumber());
        List<UserVO> users = userDAO.selectByForbid(user);
        return ResultCache.getListDataOk(total,"users",users);
    }

    @Override
    public Result selectUser(User user) {
        int total = userDAO.selectTotal(user);
        user.setPage((user.getPage()-1)*user.getNumber());
        List<UserVO> users = userDAO.select(user);
        return ResultCache.getListDataOk(total,"users",users);
    }

    @Override
    public Result selectUserByUsernameVague(User user) {
        user.setUsername("%"+user.getUsername()+"%");
        int total = userDAO.selectTotalByUsernameVague(user);
        user.setPage((user.getPage()-1)*user.getNumber());
        List<UserVO> users = userDAO.selectByUsernameVague(user);
        return ResultCache.getListDataOk(total,"users",users);
    }

    @Override
    public Result selectExaminer(User user) {
        int total = userDAO.selectTotalExaminer(user);
        user.setPage((user.getPage()-1)*user.getNumber());
        List<UserVO> users = userDAO.selectExaminer(user);
        return ResultCache.getListDataOk(total,"users",users);
    }

    @Override
    public Result addExaminer(User user) {
        forbidUtil.updateUserAddExaminer(user.getUserId());
        return ResultCache.OK;
    }

    @Override
    public Result deleteExaminer(User user) {
        forbidUtil.updateUserDeleteExaminer(user.getUserId());
        return ResultCache.OK;
    }



}